package com.itheima.reggie.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.*;
import com.itheima.reggie.domain.User;
import com.itheima.reggie.dto.LoginDto;
import com.itheima.reggie.mapper.UserMapper;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.util.Map;
import java.util.Random;

@Slf4j
@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SmsTemplate smsTemplate;
    @Autowired
    private UserMapper userMapper;


    //发送短信
    @Override
    public void sendMsg(String phone) {
        //生成六位随机数
        String code = RandomUtil.randomNumbers(6);
        code = "123"; // todo 产品上线之前，需要实现真实短信发送
        //执行的发信息方法
        // smsTemplate.sendSms(phone,code);
        log.info("发送短信成功：{}", code);
        ValueOperations valueOperations = redisTemplate.opsForValue();
        //发送验证码
        valueOperations.set(Constant.USER_CODE + phone, code, Duration.ofSeconds(300));


    }

    //登录 注册功能
    @Override
    public String login(String phone, String code) {
        //取出数据库的验证码
        String redisCode = (String) redisTemplate.opsForValue().get(Constant.USER_CODE + phone);


        if (!StrUtil.equals(redisCode, code)) {
            throw new CustomException("你输入的验证码不正确");
        }
        //根据手机号找用户 select * from user where phone =？
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        //构建条件
        qw.eq(User::getPhone, phone);
        //按手机查询用户
        User user = userMapper.selectOne(qw);
        //如果查询到为空 就注册 = 创建一个新的user
        if (user == null) {
             user = new User();
            user.setPhone(phone);
            user.setStatus(1);
            userMapper.insert(user);
        }

        Map<String, Object> userMap = BeanUtil.beanToMap(user);


        String token = JwtUtil.createToken(userMap);
        redisTemplate.delete(Constant.USER_CODE + phone);


        return token;
    }
}
